import router from '@system.router';
import prompt from '@system.prompt';
import * as userService from '../../common/userService.js';
import * as syncService from '../../common/syncService.js';

export default {
    data: {
        username: '',
        password: '',
        isLoading: false,
        loadingText: '正在登录...',
        loginError: false,
        errorMessage: ''
    },
    
    handleUsernameChange(e) {
        this.username = e.value;
        this.loginError = false;
    },
    
    handlePasswordChange(e) {
        this.password = e.value;
        this.loginError = false;
    },
    
    async handleLogin() {
        if (!this.username || !this.password) {
            this.loginError = true;
            this.errorMessage = '用户名和密码不能为空';
            return;
        }
        
        this.isLoading = true;
        this.loadingText = '正在登录...';
        
        try {
            const loginResult = await userService.login(this.username, this.password);
            
            if (loginResult.success) {
                this.loadingText = '登录成功，正在同步数据...';
                
                // 登录成功后同步数据
                try {
                    await syncService.syncWithPhone();
                    
                    prompt.showToast({
                        message: '登录成功',
                        duration: 1500
                    });
                    
                    // 返回首页
                    setTimeout(() => {
                        router.back();
                    }, 1500);
                } catch (syncError) {
                    console.error('同步数据失败:', syncError);
                    
                    prompt.showToast({
                        message: '登录成功，但同步数据失败',
                        duration: 2000
                    });
                    
                    // 返回首页
                    setTimeout(() => {
                        router.back();
                    }, 2000);
                }
            } else {
                this.isLoading = false;
                this.loginError = true;
                this.errorMessage = loginResult.message || '登录失败，请检查用户名和密码';
            }
        } catch (error) {
            console.error('登录请求失败:', error);
            
            this.isLoading = false;
            this.loginError = true;
            this.errorMessage = '登录请求失败，请检查网络连接';
        }
    },
    
    handleBack() {
        router.back();
    }
}; 